﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using TWS.Client;

public partial class admin_ChiTietLoaiSanPham : BaseAdminPage
{
    protected void btnOK_OnClick(object sender, EventArgs e)
    {
        //Page.Validate();
        //if (!Page.IsValid) return;
        //LoaiSanPhamHelper spHP = new LoaiSanPhamHelper();
        //LoaiSanPhamDataSet spDS = new LoaiSanPhamDataSet();
        //LoaiSanPhamDataSet.LoaiSanPhamRow LoaiSanPhammoi = spDS.LoaiSanPham.NewLoaiSanPhamRow();
        //LoaiSanPhammoi.TenLoaiSanPham = txtTenLoaiSanPham.Text;
        //LoaiSanPhammoi.LoaiLoaiSanPham = Convert.ToInt32(ddlLoaiCon.SelectedValue);
        //LoaiSanPhammoi.HangSanXuat = txtHangSanXuat.Text;
        //LoaiSanPhammoi.ChungLoai = txtChungLoai.Text;
        //LoaiSanPhammoi.Gia = Convert.ToInt32(txtGia.Text);
        //////UploadImage();
        //if (txtHinhAnh.Text == string.Empty)
        //{
        //    txtHinhAnh.Text = "noimage.jpg";
        //}
        //LoaiSanPhammoi.HinhAnh = txtHinhAnh.Text;
        //LoaiSanPhammoi.LoaiSanPhamMoi = ckLoaiSanPhamMoi.Checked;
        //LoaiSanPhammoi.ThuTu = Convert.ToInt32(txtThuTu.Text);
        //LoaiSanPhammoi.NgayDang = DateTime.Now;

        //LoaiSanPhammoi.TongQuan = txtTongQuan.Text;
        //LoaiSanPhammoi.ThongSoKyThuat = txtThongSo.Text;
        //LoaiSanPhammoi.Album = txtAlbum.Text;
        //spDS.LoaiSanPham.AddLoaiSanPhamRow(LoaiSanPhammoi);
        //spHP.SaveLoaiSanPham(spDS);
        //RedirectPage(Request.RawUrl, true);
        SaveData();
    }

    private LoaiSanPhamDataSet m_LoaiSanPhamDataSet;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            LoadData();
            try
            {
                string mode = Request.QueryString["mode"];
                bool isNew = false;
                if (mode != "edit")
                {
                    isNew = true;
                }
                string key = Request.QueryString["id"];
                if (!isNew)
                {
                    if (key != null && key != string.Empty)
                    {
                        LoadData(key);
                    }
                }
                else
                {
                    m_LoaiSanPhamDataSet = new LoaiSanPhamDataSet();

                    LoaiSanPhamDataSet.LoaiSanPhamRow danhMuc = m_LoaiSanPhamDataSet.LoaiSanPham.NewLoaiSanPhamRow();
                    danhMuc.LoaiSanPhamChaID = -1;
                    danhMuc.HinhAnh = "noimage.jpg";
                    m_LoaiSanPhamDataSet.LoaiSanPham.AddLoaiSanPhamRow(danhMuc);
                    Session[this.Request.Url.AbsolutePath.ToString() + "_" + "Data"] = m_LoaiSanPhamDataSet;
                    LoaiSanPhamDataSet lspDS = new LoaiSanPhamHelper().LoadLoaiSanPham(Convert.ToInt32(Request.QueryString["loaichaID"]));
                    ddlLoaiCha.Items.Add(new ListItem(lspDS.LoaiSanPham[0].TenLoaiSanPham,lspDS.LoaiSanPham[0].LoaiSanPhamID.ToString()));
                    ddlLoaiCha.SelectedValue = lspDS.LoaiSanPham[0].LoaiSanPhamID.ToString();
                    ddlLoaiCha.Enabled= false;

                    if (!danhMuc.IsHinhAnhNull()) txtHinhAnh.Text = danhMuc.HinhAnh;
                    string saveLocation = MyFilePathHelper.GetImageFolderURL(this);
                    this.imageDemons.Src = saveLocation + txtHinhAnh.Text;
                }
                if (Request.QueryString["loaichaID"]!=null)
                {
                    pnThemMoi.Visible = false;
                    upHinh.Visible = false;
                }
            }
            catch (Exception ex)
            {
                //DisplayMesseage(ex.Message);
                this.RedirectPage("pgError.aspx", false);
            }
        }
    }

    private void LoadData(string benhLyId)
    {
        int itemId;
        if (int.TryParse(benhLyId, out itemId))
        {
            LoaiSanPhamHelper helper = new LoaiSanPhamHelper();
            LoaiSanPhamDataSet tempDs = helper.LoadLoaiSanPham(itemId);


            LoaiSanPhamDataSet.LoaiSanPhamRow danhMuc = tempDs.LoaiSanPham.FindByLoaiSanPhamID(itemId);
            m_LoaiSanPhamDataSet = new LoaiSanPhamDataSet();
            m_LoaiSanPhamDataSet.LoaiSanPham.ImportRow(danhMuc);

            Session[this.Request.Url.AbsolutePath.ToString() + "_" + "Data"] = m_LoaiSanPhamDataSet;

            txtHinhAnh.Text = "noimage.jpg";
            //if (!BaiVietHay.IsHinhAnhNull()) {
            if (!danhMuc.IsHinhAnhNull()) txtHinhAnh.Text = danhMuc.HinhAnh;

            string saveLocation = MyFilePathHelper.GetImageFolderURL(this);
            this.imageDemons.Src = saveLocation + txtHinhAnh.Text;

            txtTenSanPham.Text = danhMuc.TenLoaiSanPham;
            lbTenSanPham.Text = danhMuc.TenLoaiSanPham;
            if (!danhMuc.IsLoaiSanPhamChaIDNull()) ddlLoaiCha.SelectedValue = danhMuc.LoaiSanPhamChaID.ToString();
            LoadBannerQuangCao(danhMuc.LoaiSanPhamID);
            //if (!BaiVietHay.IsHinhAnhNull()) {
            //}
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {

    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        this.RedirectLastVisitedPage();
    }

    private void SaveData()
    {
        try
        {
            string mode = Request.QueryString["mode"];
            m_LoaiSanPhamDataSet = (LoaiSanPhamDataSet)Session[this.Request.Url.AbsolutePath.ToString() + "_" + "Data"];
            //SetViewMode(canEdit);
            LoaiSanPhamDataSet.LoaiSanPhamRow danhMuc = m_LoaiSanPhamDataSet.LoaiSanPham[0];

            danhMuc.TenLoaiSanPham = txtTenSanPham.Text;
            danhMuc.LoaiSanPhamChaID = Convert.ToInt32(ddlLoaiCha.SelectedValue);

            UploadImage();
            if (txtHinhAnh.Text == string.Empty)
            {
                txtHinhAnh.Text = "noimage.jpg";
            }
            danhMuc.HinhAnh = txtHinhAnh.Text;

            LoaiSanPhamHelper helper = new LoaiSanPhamHelper();
            helper.SaveLoaiSanPham(m_LoaiSanPhamDataSet);
        }
        catch (Exception ex)
        {
            //DisplayMesseage(ex.Message);
            this.RedirectPage("pgError.aspx", false);
        }
        this.RedirectPage("QuanLyDanhMucSanPham.aspx", false);
    }


    private void UploadImage()
    {
        if (txtHinhAnh.Text != string.Empty)
        {
            //delete old image
            try
            {
                string saveLocation = MyFilePathHelper.GetImageFolderURL_Saving(this);
                MyFilePathHelper.DeleteResource(saveLocation, txtHinhAnh.Text);
            }
            catch (Exception)
            {
            }
            finally
            {
                txtHinhAnh.Text = "noimage.jpg";
            }
            //postpone new image
        }
        //save new image
        if (this.inputFile.PostedFile != null && this.inputFile.PostedFile.ContentLength > 0)
        {
            string fn = System.IO.Path.GetFileName(inputFile.PostedFile.FileName);
            string path = MyFilePathHelper.GetImageFolderURL_Saving(this);
            fn = MyFilePathHelper.AppendTimeStamp(fn);
            string saveLocation = path + fn;

            inputFile.PostedFile.SaveAs(saveLocation);
            FileStream fs = File.Open(saveLocation, FileMode.Open, FileAccess.Read);
            byte[] inByte = new byte[fs.Length];
            fs.Read(inByte, 0, inByte.Length);
            fs.Close();
            MyFilePathHelper.DeleteResource(path, fn);
            ImagesConvertHelper iconvert = new ImagesConvertHelper();
            string filename;
            if (iconvert.ConvertImage(saveLocation, inByte, 6, out filename) == false)
                txtHinhAnh.Text = string.Empty;
            else
            {
                txtHinhAnh.Text = fn + ".JPG";
            }
        }
    }


    private void LoadData()
    {
        LoaiSanPhamDataSet lspDS = new LoaiSanPhamHelper().LoadLoaiSanPhamCha();
        ddlLoaiCha.DataSource = lspDS.LoaiSanPham;
        ddlLoaiCha.DataTextField = "TenLoaiSanPham";
        ddlLoaiCha.DataValueField = "LoaiSanPhamID";
        ddlLoaiCha.DataBind();

        //int id = Convert.ToInt32(ddlLoaiCha.SelectedValue);
        //LoaiSanPhamDataSet lspDSCon = new LoaiSanPhamHelper().LoadLoaiSanPhamCon(id);
        //ddlLoaiCon.DataSource = lspDSCon.LoaiSanPham;
        //ddlLoaiCon.DataTextField = "TenLoaiSanPham";
        //ddlLoaiCon.DataValueField = "LoaiSanPhamID";
        //ddlLoaiCon.DataBind();

        //ddlCon.DataSource = lspDSCon.LoaiSanPham;
        //ddlCon.DataTextField = "TenLoaiSanPham";
        //ddlCon.DataValueField = "LoaiSanPhamID";
        //ddlCon.DataBind();
    }

    private void LoadBannerQuangCao(int loaisanpham)
    {
        string tmpPage = Request.QueryString["pg"];
        int currentPage = 1;
        if (tmpPage != null && tmpPage != "")
        {
            currentPage = Convert.ToInt32(tmpPage);
        }

        LoaiSanPhamDataSet spDs = new LoaiSanPhamHelper().LoadLoaiSanPhamCon(loaisanpham);

        repSanPham.DataSource = spDs.LoaiSanPham;
        repSanPham.DataBind();

        TotalRecord = spDs.LoaiSanPham.Count;

        ResultCount.Text = TotalRecord.ToString();

        //Paging page = getPagingObject(TotalRecord, currentPage, PagingSize);

        //PageString = page.BuildPaging();
    }

    protected void learnMoreButton_Click(object sender, EventArgs e)
    {
        int id = Convert.ToInt32(((Button)sender).CommandArgument);
        LoaiSanPhamDataSet bannerDs = new LoaiSanPhamHelper().LoadLoaiSanPham(id);
        bannerDs.LoaiSanPham[0].Delete();
        new LoaiSanPhamHelper().SaveLoaiSanPham(bannerDs);
        RedirectPage(Request.RawUrl, true);
    }

    protected void repSanPham_OnItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Button repCon = ((Button)e.Item.FindControl("learnMoreButton"));
            repCon.Attributes.Add("onclick", "if (!confirm('Xóa dữ liệu?')) return;");
        }
    }

    protected void bttThemMoi_OnClick(object sender, EventArgs e)
    {
        RedirectPage("ChiTietLoaiSanPham.aspx?mode=new&loaichaID="+Request.QueryString["id"],true);
    }

}